package com.notepad.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.notepad.blog.common.exception.ApiAsserts;
import com.notepad.blog.domain.BmsComment;
import com.notepad.blog.domain.UmsUser;
import com.notepad.blog.domain.dto.CommentDTO;
import com.notepad.blog.domain.vo.CommentVO;
import com.notepad.blog.mapper.BmsCommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @ClassName BmsCommentService
 * @description:
 * @author: 一粒麦子
 * @Date 2021/2/13 21:26
 **/
@Service
public class BmsCommentService extends ServiceImpl<BmsCommentMapper, BmsComment> {

    @Autowired
    private BmsCommentMapper commentMapper;

    @Autowired
    private UmsUserService userService;

    /**
     * 评论列表
     *
     * @param topicid
     * @return
     */
    public List<CommentVO> getCommentsByTopicID(String topicid) {
        List<CommentVO> commentVOList = commentMapper.getCommentsByTopicID(topicid);
        return commentVOList;
    }

    public BmsComment addComment(CommentDTO dto, String userName) {

        // 判断评论内容
        String content = dto.getContent();

        if (StringUtils.isEmpty(content) || content.length() < 2) {
            ApiAsserts.fail("评论内容不能少于2个字符");
        }

        // 获取用户信息
        UmsUser umsUser = userService.getOne(new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getUsername, userName));
        Assert.notNull(umsUser, "用户不存在");

        BmsComment comment = BmsComment.builder().userId(umsUser.getId())
                .content(dto.getContent())
                .postId(dto.getTopic_id())
                .createTime(new Date())
                .build();
        this.save(comment);
        return comment;
    }
}
